import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 银行流水数据
const bankData = ref([])

// 分页配置
const bankPagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 筛选条件
const bankFilters = reactive({
  dateRange: 'all',
  search: ''
})

// 从Chrome存储中获取银行流水数据
const fetchBankData = async () => {
  return new Promise<any[]>((resolve) => {
    chrome.storage.local.get(['capturedRequests'], (result) => {
      const allRequests = Array.isArray(result.capturedRequests) ? result.capturedRequests : []
      
      // 筛选出银行流水数据（根据URL或数据类型）
      const bankRequests = allRequests.filter(request => {
        // 优先根据dataType字段筛选
        if (request.dataType) {
          return request.dataType === 'bank'
        }
        // 根据拦截规则匹配银行流水数据
        return request.url && (
          request.url.includes('bank') || 
          request.url.includes('ebank') ||
          (request.dataType && request.dataType === 'bank')
        )
      })
      
      // 处理数据格式
      const formattedData = bankRequests.map((request: any, index) => {
        // 提取数据预览
        let preview = '{}'
        try {
          if (request.response) {
            preview = JSON.stringify(request.response, null, 2)
          } else if (request.requestBody) {
            preview = JSON.stringify(request.requestBody, null, 2)
          }
        } catch (e) {
          preview = '{}'
        }
        
        // 截取预览内容
        if (preview.length > 100) {
          preview = preview.substring(0, 100) + '...'
        }
        
        return {
          id: request.id || index + 1,
          date: request.timestamp ? new Date(request.timestamp).toLocaleString() : new Date().toLocaleString(),
          source: request.url || '未知来源',
          preview: preview,
          status: request.synced ? '已同步' : '待同步'
        }
      })
      
      resolve(formattedData)
    })
  })
}

// 渲染银行流水表格
const renderBankTable = async () => {
  try {
    const data: any[] = await fetchBankData()
    bankPagination.total = data.length
    
    // 分页处理
    const start = (bankPagination.currentPage - 1) * bankPagination.pageSize
    const end = start + bankPagination.pageSize
    bankData.value = data.slice(start, end)
  } catch (error) {
    console.error('获取银行流水数据失败:', error)
    ElMessage.error('获取银行流水数据失败')
  }
}

// 银行流水分页处理
const handleBankPageChange = (page) => {
  bankPagination.currentPage = page
  renderBankTable()
}

// 单条同步银行流水
const syncSingleBank = (row) => {
  ElMessage.success(`银行流水数据(ID: ${row.id})同步成功`)
}

// 删除银行流水
const deleteBank = (row) => {
  ElMessageBox.confirm(`确定要删除银行流水数据(ID: ${row.id})吗？`, '删除数据', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('删除成功')
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 组件挂载时获取数据
onMounted(() => {
  renderBankTable()
})

export function useBankData() {
  return {
    bankData,
    bankPagination,
    bankFilters,
    renderBankTable,
    handleBankPageChange,
    syncSingleBank,
    deleteBank
  }
}